<template>
  <n-grid cols="2 s:2 m:2 l:3 xl:3 2xl:3" responsive="screen">
    <n-grid-item>
      <n-form :label-width="80" :model="formRef" :rules="rules" ref="formRef">
        <n-form-item label="姓名" path="name">
          <n-input v-model:value="formRef.name" placeholder="请输入姓名"/>
        </n-form-item>

        <n-form-item label="部门" path="dept">
          <n-input placeholder="请输入所在部门" v-model:value="formRef.dept"/>
        </n-form-item>

        <n-form-item label="手机号" path="telephone">
          <n-input placeholder="请输入手机号" v-model:value="formRef.telephone"/>
        </n-form-item>

        <n-form-item label="密码" path="password">
          <n-input placeholder="请输入密码" type="password" :maxlength="12"
                   show-password-on="mousedown" v-model:value="formRef.password"/>
        </n-form-item>

        <div>
          <n-space>
            <n-button type="primary" @click="formSubmit">更新基本信息</n-button>
          </n-space>
        </div>
      </n-form>
    </n-grid-item>
  </n-grid>
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue';
import {useMessage} from 'naive-ui';
import {useUserStore} from "@/store/modules/user";
import {addUser, editUser} from "@/api/system/user";

const user = useUserStore();

const rules = {
  name: {
    required: true,
    message: '请输入昵称',
    trigger: 'blur',
  },
  dept: {
    required: true,
    message: '请输入部门',
    trigger: 'blur',
  },
  telephone: {
    required: true,
    message: '请输入联系电话',
    trigger: 'input',
  },
};
const message = useMessage();

const formRef: any = ref({
  id: '',
  name: '',
  telephone: '',
  dept: '',
  password: '',
});

function formSubmit() {
  formRef.value.validate(async (errors) => {
    if (!errors) {
      let res = await editUser({
        id: formRef.value.id,
        name: formRef.value.name,
        telephone: formRef.value.telephone,
        dept: formRef.value.dept,
        password: formRef.value.password,
      });
      if (res.code === 200) {
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    } else {
      message.error('验证失败，请填写完整信息');
    }
  });
}

onMounted(() => {
  Object.assign(formRef.value, user.getUserInfo)
})
</script>
